﻿#include "amath.h"

using namespace anip;

wstring anip::toString(invec2 x)
{
	// see above
	static char buf[100];
	snprintf(buf, sizeof(buf), "(%g, %g)", x.x, x.y);
	return utf8s2ws(buf);
}

template<>
void anip::binaryWrite(const vec2& val, std::ostream& o)
{
	binaryWrite(val.x, o);
	binaryWrite(val.y, o);
}

template<>
void anip::binaryRead(vec2& val, std::istream& i)
{
	binaryRead(val.x, i);
	binaryRead(val.y, i);
}

bool math::inRectangle(invec2 p, invec2 rp, invec2 rs)
{
	vec2 d = p - rp;
	return d.x >= 0 && d.y >= 0 && d.x <= rs.x && d.y <= rs.y;
}

void math::rectangleIntersect(
	invec2 p1, invec2 s1,
	invec2 p2, invec2 s2,
	outvec2 outp, outvec2 outs)
{
	outp = { 
		std::max(p1.x, p2.x),
		std::max(p1.y, p2.y) };
	outs = {
		std::max(0.0f, std::min(p1.x + s1.x, p2.x + s2.x) - outp.x),
		std::max(0.0f, std::min(p1.y + s1.y, p2.y + s2.y) - outp.y) };
}

vec2 math::normal(invec2 v)
{
	return normalize(vec2{ -v.y, v.x });
}

vec2 math::rotate(invec2 v, float rad)
{
	float c = cos(rad);
	float s = sin(rad);
	return { v.x * c - v.y * s, v.x * s + v.y * c };
}